﻿using System;
using System.IO;
using System.Text;
using System.Linq; // 添加LINQ支持

namespace splitTxt
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("=== 文本文件分割工具 ===");
            
            try
            {
                // 显示菜单
                Console.WriteLine("1. 分割文件");
                Console.WriteLine("2. 查看已分割文件列表");
                Console.Write("请选择操作 (1/2): ");
                string? choice = Console.ReadLine();
                choice = string.IsNullOrEmpty(choice) ? "1" : choice.Trim();
                
                if (choice == "1")
                {
                    SplitFile();
                }
                else if (choice == "2")
                {
                    ListSplitFiles();
                }
                else
                {
                    Console.WriteLine("无效选择，默认执行分割操作");
                    SplitFile();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
        
        static void SplitFile()
        {
            // 获取用户输入
            Console.Write("请输入要分割的文件路径: ");
            string? filePath = Console.ReadLine();
            filePath = !string.IsNullOrEmpty(filePath) ? filePath.Trim('"') : string.Empty;
            
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                Console.WriteLine("错误: 文件不存在或路径无效!");
                return;
            }

            Console.Write("请输入每个小文件的最大大小(MB): ");
            if (!double.TryParse(Console.ReadLine(), out double maxSizeMB) || maxSizeMB <= 0)
            {
                Console.WriteLine("错误: 请输入有效的文件大小!");
                return;
            }

            // 转换为字节
            long maxSizeBytes = (long)(maxSizeMB * 1024 * 1024);
            
            // 执行分割
            SplitTextFile(filePath, maxSizeBytes);
            
            Console.WriteLine("文件分割完成!");
        }
        
        static void ListSplitFiles()
        {
            Console.Write("请输入要查看的目录路径(留空则使用当前目录): ");
            string? dirPath = Console.ReadLine();
            dirPath = string.IsNullOrEmpty(dirPath) ? string.Empty : dirPath.Trim('"');
            
            if (string.IsNullOrEmpty(dirPath))
            {
                dirPath = Directory.GetCurrentDirectory();
            }
            
            if (!Directory.Exists(dirPath))
            {
                Console.WriteLine("错误: 目录不存在!");
                return;
            }
            
            Console.Write("请输入文件名前缀(留空则显示所有part文件): ");
            string? prefix = Console.ReadLine();
            prefix = string.IsNullOrEmpty(prefix) ? string.Empty : prefix.Trim();
            
            // 获取所有分割文件
            var files = Directory.GetFiles(dirPath, $"{prefix}*part*.*")
                .OrderBy(f => {
                    // 提取part后面的数字部分进行自然排序
                    string fileName = Path.GetFileName(f);
                    int startIndex = fileName.IndexOf("part") + 4;
                    int endIndex = fileName.IndexOf(".", startIndex);
                    if (endIndex < 0) endIndex = fileName.Length;
                    string numberPart = fileName.Substring(startIndex, endIndex - startIndex);
                    if (int.TryParse(numberPart, out int number))
                        return number;
                    return 0;
                })
                .ToList();
            
            if (files.Count == 0)
            {
                Console.WriteLine("未找到分割文件!");
                return;
            }
            
            Console.WriteLine("\n按自然顺序排列的分割文件列表:");
            Console.WriteLine("----------------------------------------");
            Console.WriteLine("序号\t文件名\t\t大小(MB)");
            Console.WriteLine("----------------------------------------");
            
            for (int i = 0; i < files.Count; i++)
            {
                string fileName = Path.GetFileName(files[i]);
                double sizeMB = new FileInfo(files[i]).Length / (1024.0 * 1024.0);
                Console.WriteLine($"{i+1}\t{fileName}\t{sizeMB:F2}");
            }
            
            Console.WriteLine("----------------------------------------");
            Console.WriteLine($"共找到 {files.Count} 个分割文件");
        }

        static void SplitTextFile(string filePath, long maxSizeBytes)
        {
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            string fileExtension = Path.GetExtension(filePath);
            string directory = Path.GetDirectoryName(filePath);
            if (string.IsNullOrEmpty(directory))
                directory = Directory.GetCurrentDirectory();

            int fileIndex = 1; // ← 作用域挪到 using 外
            long currentFileSize = 0;
            var currentContent = new StringBuilder();

            using (var reader = new StreamReader(filePath, Encoding.UTF8))
            {
                string? line;
                while ((line = reader.ReadLine()) != null)
                {
                    long lineSize = Encoding.UTF8.GetByteCount(line + Environment.NewLine);

                    // 如果当前块不空，且加这一行会超限，先落盘
                    if (currentFileSize + lineSize > maxSizeBytes && currentContent.Length > 0)
                    {
                        SaveSplitFile(directory, fileName, fileExtension, fileIndex, currentContent.ToString());
                        fileIndex++;
                        currentFileSize = 0;
                        currentContent.Clear();
                    }

                    currentContent.AppendLine(line);
                    currentFileSize += lineSize;
                }
            }

            if (currentContent.Length > 0)
            {
                SaveSplitFile(directory, fileName, fileExtension, fileIndex, currentContent.ToString());
            }

            Console.WriteLine($"文件已分割为 {fileIndex} 个部分");
        }

        static void SaveSplitFile(string directory, string fileName, string extension, int index, string content)
        {
            // 使用固定长度的数字格式确保正确排序
            string outputFileName = $"{fileName}_part{index:D3}{extension}";
            string outputPath = Path.Combine(directory, outputFileName);

            // 避免写入 UTF-8 BOM（可选）
            File.WriteAllText(outputPath, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));

            long fileSize = new FileInfo(outputPath).Length;
            double fileSizeMB = fileSize / (1024.0 * 1024.0);
            Console.WriteLine($"已创建: {outputFileName} ({fileSizeMB:F2} MB)");
        }
    }
}
